package com.itheima.reggie.controller;

import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 购物车管理
 */
@RestController
@RequestMapping("shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 用户购物车展示
     */
    @GetMapping("list")
    public R<List<ShoppingCart>> list(){
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = shoppingCartService.lambdaQuery()
            .eq(ShoppingCart::getUserId, userId)
            .list();

        return R.success(shoppingCartList);
    }


    /**
     * 添加购物项
     */
    @PostMapping("add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        //添加一套数据到shoppingCat表中
        Long userId = BaseContext.getCurrentId();
        ShoppingCart one = shoppingCartService.lambdaQuery()
            .eq(ShoppingCart::getUserId,userId)
            .eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId())
            .eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId())
            .one();
        if(one != null){
            //购物车有数据，修改数量
            one.setNumber(one.getNumber()+1);
            shoppingCartService.updateById(one);
            return R.success(one);

        }else {
            //购物车没有数据，添加一条数据到数据库中
            //设置用户id
            shoppingCart.setUserId(userId);
            shoppingCart.setNumber(1);
            shoppingCartService.save(shoppingCart);
            return R.success(shoppingCart);
        }
    }


}
